package filmring
//import groovy.sql.Sql

class MovieService {
    // def dataSource   // the Spring-Bean "dataSource" is auto-injected

    /**
     * Takes a parameter numberOfResults and returns a list of the top n number of rated movies
     * @param numberOfResults
     * @return
     */
    public List<Movie> getTopMovies(int numberOfResults){
        List <Movie> searchResults = []

        /*
            def db = new Sql(dataSource)    // Create a new instance of groovy.sql.Sql with the DB of the Grails app
            query_text ="\
                            SELECT TOP ${numberOfResults} Rating.movie \
                            FROM Movie INNER JOIN Rating ON Movie = Rating.movie \
                            GROUP BY Rating.movie \
                            ORDER BY Avg(Rating.rating) DESC
                        "
            searchResults = db.rows(query_text)     // Perform the query
         */

        //searchResults = getTopNMovies(numberOfResults)

        List<Rating> matchedRatings = Rating.executeQuery("SELECT r FROM Rating as r GROUP BY r.movie ORDER BY Avg(r.rating) DESC limit ${numberOfResults}")
        for(Rating rating : matchedRatings){
             searchResults.add(rating.movie)
        }
        return searchResults
    }

    /**
     * Takes a parameter numberOfResults and returns a list of the top n most recently released movies
     * @param numberOfResults
     * @return
     */
    public List<Movie> getNewReleases(int numberOfResults){
        List<Movie> searchResults = Movie.executeQuery("SELECT m from Movie as m order by m.releaseDate DESC limit ${numberOfResults}")
        //Movie.list()
        if(searchResults.size() > 5) {
            searchResults = searchResults.subList(0,5)
        }
        return searchResults
    }

    /**
     * Takes a parameter numberOfResults and returns a list of the top n number of rated movies
     * @param numberOfResults
     * @return
     */
    public List<Movie> getTopNMovies(int numberOfResults) {
        //Searches through the database and picks out the top rated movies; equivalent to getTopMovies but does not use sql
        def p = new PopularityComparator()
        //Movie.list().max(p)
        def topN = []
        def mList = Movie.list()
        mList.sort(p)
        for(int n=0;n < numberOfResults; n++) {
            topN.add(mList[mList.size()-1-n])
        }
        return topN
    }

    /**
     * Takes a movie and returns its average rating as a string
     * @param movie
     * @return
     */
    public String getAvgRating(Movie movie){
        List<Rating> ratings = Rating.findAllByMovie(movie)
        if(ratings==null){
            return "Not Yet Rated"
        }
        if(ratings.size()==0){
            return "Not Yet Rated"
        }
        int totalRatings = 0
        for(Rating rating : ratings){
            totalRatings+=rating.rating
        }
        return "${((totalRatings*1.0)/ratings.size())}"
    }



}
